package m.store.action;

import m.appserver.AuthInfoUtil;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.Text;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.element.other.Param;
import m.html.form.*;
import m.html.list.*;
import m.store.model.GoodsStockRecord;
import m.store.model.OrderModel;
import m.store.model.SaleInfo;
import m.store.model.StockInfo;
import m.store.service.StockInfoService;
import m.store.service.StoreNumberService;
import m.store.util.ColorUtil;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ActionMeta(name = "store/stockInfo")
public class StockInfoAction extends OrderModelAction {
    private StockInfo model;
    private List<GoodsStockRecord> goodsList;

    /**
     * 保存
     */
    @RequestMeta(transaction = true,logTitle = "入库信息",logDescription = "保存入库信息")
    public JSONMessage doSave() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        String msg=getService(StockInfoService.class).save(model,goodsList);
        return new JSONMessage(0,msg)
                .push("model", model);
    }
    @RequestMeta(transaction = true,logTitle = "入库信息",logDescription = "保存并提交入库信息")
    public JSONMessage doSaveAndSubmit() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        getService(StockInfoService.class).saveAndSubmit(model,goodsList);
        return new JSONMessage(0,"提交成功");
    }
    @RequestMeta(transaction = true,logTitle = "入库信息",logDescription = "删除入库信息")
    public JSONMessage doDelete() throws Exception {
        getService(StockInfoService.class).delete(model.getOid(),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"删除成功");
    }
    @RequestMeta(transaction = true,logTitle = "入库信息",logDescription = "审核通过入库信息")
    public JSONMessage doCheck() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Stock);
        getService(StockInfoService.class).check(model.getOid(),model.getStockDate(),model.getRemark(),PowerUtil.getSessionStore(true),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"审核成功");
    }
    @RequestMeta(transaction = true,logTitle = "入库信息",logDescription = "退回入库信息")
    public JSONMessage doRefund() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Stock);
        getService(StockInfoService.class).refund(model.getOid(),PowerUtil.getSessionStore(true),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"退回成功");
    }
    /*
     * 编辑入库
     */
    public VueResult toEdit() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
            goodsList=ModelQueryList.getModelList(GoodsStockRecord.class,new String[]{"*","goods.*"},null,
                    QueryCondition.eq("stock.oid",model.getOid()), QueryOrder.asc("oid"));
        }else{
            model=new StockInfo();
            model.setOrderNo(StoreNumberService.getNextStockNumber());
            model.setStatus(OrderModel.Status_Register);
            model.setType(StockInfo.Type_Stock);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setInputDate(new Date());
            model.setStockDate(new Date());
            goodsList=new ArrayList<>();
        }
        boolean edit=OrderModel.Status_Register.equals(model.getStatus());
        boolean check=OrderModel.Status_Check.equals(model.getStatus())&&PowerUtil.hasPower(PowerUtil.Stock);
        ModelForm form = new ModelForm("入库信息");
        form.setSubTitle(ListElement.tag("model.type","m.store.model.StockInfo!type",ColorUtil.getStockType(),false).toString());
        form.addItem(
            FormHtml.inputStyle("入库单号","{{model.orderNo}}"),
            FormInput.selectOneModel("供货客户", "model","guest","'action/store/guestInfo/selectOneGuest'",1300,"<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2).setEdit(edit),
            FormHtml.inputStyle("登记人","{{model.inputUser.realname}} {{model.inputDate}}"),
            FormHtml.inputStyle("入库金额","<b>{{goodsList.length?formatNumber(model.stockAmount,'#,##0.00'):'请添加明细'}}</b>"),
            FormInput.date("入库日期","model.stockDate").setEdit(edit||check).setRequired(true),
            FormInput.textarea("备注","model.remark").setSpan(3).setEdit(edit||check)
        )
        .addData("model",model)
        .addButton(
            edit?FormButton.pri("保存","doSave"):null,
            edit?FormButton.succ("提交","doSaveAndSubmit").setConfirm("确定要提交吗？"):null,
            check?getCheckFormButton(model.getOid()):null,
            check?FormButton.warn("退回","doRefund").setConfirm("确定要退回吗？"):null
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model,goodsList:this.goodsList}")
                .fillData("model"),
            FormEvent.doJson("doSaveAndSubmit",actionUrl("doSaveAndSubmit"),"{model:this.model,goodsList:this.goodsList}")
                .success("backFlag"),
            FormEvent.doJson("doCheck",actionUrl("doCheck"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.doJson("doRefund",actionUrl("doRefund"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        TableForm form1=new TableForm("入库商品").setEdit(edit,true,"{repository:"+getDefRepParam()+",goods:{},preferential:0}",false);
        form1.setData("goodsList",goodsList)
        .addMethod(
            FormEvent.custom("editRowAfter(item)",
             "item.stockAmount=this.roundNumber((item.price||0)*(item.stockNum||0)-(item.preferential||0),2);" +
                "item.preferentialPrice=this.roundNumber(item.stockAmount/(item.stockNum||1),2);"
            ),
            FormEvent.custom("editDataAfter",
             "var sum=0.0;" +
                "for(var i=0;i<this.goodsList.length;i++){" +
                " sum+=(this.goodsList[i].stockAmount||0);" +
                "}" +
                "this.model.stockAmount=this.roundNumber(sum,2);"
            )
        )
        .setEditRowConfirm("editRowAfter")
        .setRowChangeAfter("editDataAfter")
        .addColumn(
            TableColumn.index("序号"),
            TableColumn.text("仓库","repository.oid",100)
                .setShow(new Text("{{dict('m.store.model.RepositoryInfo:"+PowerUtil.getSessionStoreOid()+"',text)}}"))
                .setEdit(TableEdit.select("m.store.model.RepositoryInfo:"+PowerUtil.getSessionStoreOid())),
            TableColumn.text("商品","goods.name",200)
                .setEdit(TableEdit.selectOneModel("'action/store/storeGoods/selectOneStoreGoods'",1100,"goods","name")),
            TableGroup.ins("剩余",
                TableColumn.number("均价","goods.surplusPrice",100).isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.goods.surplusPrice,'#,##0.00')}}")),
                TableColumn.number("数量","goods.surplusNum",80,"#,##0").isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.goods.surplusNum,'#,##0')}}"))
            ),
            TableGroup.ins("入库",
                TableColumn.number("单价","price",100).isSum(false)
                    .setEdit(TableEdit.number()),
                TableColumn.number("数量","stockNum",80,"#,##0")
                    .setEdit(TableEdit.number("#,##0",0)),
                TableColumn.number("总优惠","preferential",100)
                    .setEdit(TableEdit.number())
            ),
            TableGroup.ins("优惠后",
                TableColumn.number("单价","preferentialPrice",100).isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber((editRecord.price*editRecord.stockNum-editRecord.preferential)/editRecord.stockNum,'#,##0.00')}}")),
                TableColumn.number("金额","stockAmount",100)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.price*editRecord.stockNum-editRecord.preferential,'#,##0.00')}}"))
            ),
            TableColumn.text("备注","remark",150)
                .setEdit(TableEdit.input())
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(form1);
    }
    public VueResult toEditRefund() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
            goodsList=ModelQueryList.getModelList(GoodsStockRecord.class,new String[]{"*","goods.*","outRecord.*","outRecord.goods.*"},null,
                    QueryCondition.eq("stock.oid",model.getOid()), QueryOrder.asc("oid"));
        }else if(null!=model&& ObjectUtil.notEmptyOid(model.getRefundSale())){
            if(!ModelQueryList.getModelList(StockInfo.class, new String[]{"oid"}, null,
                QueryCondition.and(
                    QueryCondition.eq("refundSale.oid", model.getRefundSale().getOid()),
                    QueryCondition.not(QueryCondition.eq("status", OrderModel.Status_Done))
                )
            ).isEmpty()) throw new MException(this.getClass(),"已存在该订单未完成的退货，请到入库登记里查看。");
            model.setRefundSale(ModelQueryList.getModel(SaleInfo.class,model.getRefundSale().getOid(),"*","guest.*"));
            model.setGuest(model.getRefundSale().getGuest());
            model.setOrderNo(StoreNumberService.getNextStockNumber());
            model.setStatus(OrderModel.Status_Register);
            model.setType(StockInfo.Type_Refund);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setInputDate(new Date());
            model.setStockDate(new Date());
            goodsList=new ArrayList<>();
        }else{
            throw new MException(this.getClass(),"参数错误");
        }
        boolean edit=OrderModel.Status_Register.equals(model.getStatus());
        boolean check=OrderModel.Status_Check.equals(model.getStatus())&&PowerUtil.hasPower(PowerUtil.Stock);
        ModelForm form = new ModelForm("入库信息");
        form.setSubTitle(ListElement.tag("model.type","m.store.model.StockInfo!type",ColorUtil.getStockType(),false).toString());
        form.addItem(
            FormHtml.inputStyle("入库单号","{{model.orderNo}}"),
            FormHtml.inputStyle("供货客户", "<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2),
            FormHtml.inputStyle("登记人","{{model.inputUser.realname}} {{model.inputDate}}"),
            FormHtml.inputStyle("退货金额","<b>{{goodsList.length?formatNumber(model.stockAmount,'#,##0.00'):'请添加明细'}}</b>"),
            FormInput.date("退货日期","model.stockDate").setEdit(edit||check).setRequired(true),
            FormInput.textarea("备注","model.remark").setSpan(3).setEdit(edit||check)
        )
        .addData("model",model)
        .addButton(
            edit?FormButton.pri("保存","doSave"):null,
            edit?FormButton.succ("提交","doSaveAndSubmit").setConfirm("确定要提交吗？"):null,
            check?getCheckFormButton(model.getOid()):null,
            check?FormButton.warn("退回","doRefund").setConfirm("确定要退回吗？"):null
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model,goodsList:this.goodsList}")
                .fillData("model"),
            FormEvent.doJson("doSaveAndSubmit",actionUrl("doSaveAndSubmit"),"{model:this.model,goodsList:this.goodsList}")
                .success("backFlag"),
            FormEvent.doJson("doCheck",actionUrl("doCheck"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.doJson("doRefund",actionUrl("doRefund"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        TableForm form1=new TableForm("入库商品").setEdit(edit,true,"{repository:{},goods:{},outRecord:{goods:{}},preferential:0}",false);
        form1.setData("goodsList",goodsList)
        .addMethod(
            FormEvent.custom("editRowAfter(item)",
                "item.stockAmount=this.roundNumber((item.price||0)*(item.stockNum||0)-(item.preferential||0),2);" +
                "item.preferentialPrice=this.roundNumber(item.stockAmount/(item.stockNum||1),2);" +
                "item.goods=item.outRecord.goods;"
            ),
            FormEvent.custom("editDataAfter",
                "var sum=0.0;" +
                "for(var i=0;i<this.goodsList.length;i++){" +
                " sum+=(this.goodsList[i].stockAmount||0);" +
                "}" +
                "this.model.stockAmount=this.roundNumber(sum,2);"
            )
        )
        .setEditRowConfirm("editRowAfter")
        .setRowChangeAfter("editDataAfter")
        .addColumn(
            TableColumn.index("序号"),
            TableColumn.text("仓库","repository.oid",100)
                .setShow(new Text("{{dict('m.store.model.RepositoryInfo:"+PowerUtil.getSessionStoreOid()+"',text)}}"))
                .setEdit(TableEdit.select("m.store.model.RepositoryInfo:"+PowerUtil.getSessionStoreOid())),
            TableColumn.text("商品","goods.name",200)
                .setEdit(TableEdit.selectOneModel("'action/store/goodsOutRecord/selectRefundList?params[sale.oid]="+model.getRefundSale().getOid()+"'",1100,"outRecord","goods.name")),
            TableColumn.number("销售单价","outRecord.preferentialPrice",100).isSum(false)
                .setEdit(Element.tag("div").E("{{formatNumber(editRecord.outRecord.preferentialPrice,'#,##0.00')}}")),
            TableColumn.number("剩余数量","outRecord.surplusNum",80,"#,##0").isSum(false)
                .setEdit(Element.tag("div").E("{{formatNumber(editRecord.outRecord.surplusNum,'#,##0')}}")),
            TableGroup.ins("退货",
                TableColumn.number("单价","price",100).isSum(false)
                    .setEdit(TableEdit.number()),
                TableColumn.number("数量","stockNum",80,"#,##0")
                    .setEdit(TableEdit.number("#,##0",0)),
                TableColumn.number("总扣减","preferential",100)
                    .setEdit(TableEdit.number())
            ),
            TableGroup.ins("扣减后",
                TableColumn.number("单价","preferentialPrice",100).isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber((editRecord.price*editRecord.stockNum-editRecord.preferential)/editRecord.stockNum,'#,##0.00')}}")),
                TableColumn.number("金额","stockAmount",100)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.price*editRecord.stockNum-editRecord.preferential,'#,##0.00')}}"))
            ),
            TableColumn.text("备注","remark",150)
                .setEdit(TableEdit.input())
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(form1);
    }
    @RequestMeta(params = {"oper"})
    public VueResult toView(String oper) throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.name","inputUser.realname","checkUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
        }else{
            throw AuthInfoUtil.noPowerException;
        }
        boolean isStock=!StockInfo.Type_Refund.equals(model.getType());
        ModelForm form = new ModelForm("库存信息");
        form.setSubTitle(ListElement.tag("model.type","m.store.model.StockInfo!type",ColorUtil.getStockType(),false).toString());
        form.addItem(
            FormHtml.inputStyle("入库单号", "{{model.orderNo}} {{dict('m.store.model.StockInfo!status',model.status)}}"),
            FormHtml.inputStyle("登记人", "{{model.inputUser.realname}} {{formatDate(model.submitDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle("审核人", "{{model.checkUser.realname}} {{formatDate(model.checkDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle(isStock?"入库日期":"退货日期","{{formatDate(model.stockDate,'yyyy-MM-dd')}}"),
            FormHtml.inputStyle("供货客户", "<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2),
            FormHtml.inputStyle(isStock?"入库金额":"退货金额", "{{formatNumber(model.stockAmount,'#,##0.00')}}")
        ).addMethod(
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        if(isStock){
            form.addItem(
                FormHtml.inputStyle("付款金额", "{{formatNumber(model.payAmount,'#,##0.00')}} {{dict('m.store.model.StockInfo!payStatus',model.payStatus)}}"),
                FormHtml.inputStyle("尚欠金额", "{{formatNumber(model.oweAmount,'#,##0.00')}}"),
                model.getRefundAmount()>0?FormHtml.inputStyle("退款金额", "{{formatNumber(model.refundAmount,'#,##0.00')}}"):null,
                FormHtml.inputStyle("备注","{{model.remark}}").setSpan(3)
            );
        }else{
            form.addItem(
                FormHtml.inputStyle("备注","{{model.remark}}").setSpan(2)
            );
        }
        form.addData("model",model);
        LoadPage recordPage=new LoadPage("loadRecordPage",actionUrl(GoodsStockRecordAction.class,"recordList"),"{params:{'oper':'"+oper+"','stock.oid':this.model.oid,'stock.type':'"+model.getType()+"'}}")
            .setMounted("this.loadRecordPage();");
        VueFormResult result=new VueFormResult();
        result.addForm(form).addForm(recordPage);
        if(model.getRefundAmount()>0){
            LoadPage refundRecordPage=new LoadPage("loadRefundRecordPage",actionUrl(GoodsOutRecordAction.class,"refundRecordList"),"{params:{'sale.refundStock.oid':this.model.oid}}")
                .setMounted("this.loadRefundRecordPage();");
            result.addForm(refundRecordPage);
        }
        return result;
    }
    private ListColumn getTypeColumn(){
        String dict="m.store.model.StockInfo!type";
        return toElementColumn("类型", "type", 100,
            ListElement.tag(dict, ColorUtil.getStockType(),false)
        ).setAlign(Align.CENTER).setFilter(true).setDictType(dict);
    }
    /*
     * 我的入库登记列表
     */
    public VueResult myInputList() throws Exception {
        String month= DateUtil.format(new Date(),"yyyyMM");
        VueListResult result=getVueListResult("我的入库登记",StockInfo.class,actionUrl("myInputList"));
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("入库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("入库客户", "guest.name", 150, true));
        result.addCol(toNumberColumn("入库金额", "stockAmount", 100, true));
        result.addCol(toDateColumn("入库日期", "stockDate", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.addCol(toTextColumn("付款状态", "payStatus", 100, true).setDictType("m.store.model.StockInfo!payStatus"));
        result.addCol(toNumberColumn("付款金额", "payAmount", 100, true));
        result.addCol(toNumberColumn("尚欠金额", "oweAmount", 100, true));
        result.addCol(toSpaceColumn("操作", 140,
            ListElement.test("record.status=='"+OrderModel.Status_Register+"'&&record.type=='"+StockInfo.Type_Stock+"'",
                ListButton.page("修改", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Register+"'&&record.type=='"+StockInfo.Type_Refund+"'",
                ListButton.page("修改", ButtonType.PRIMARY,actionUrl("toEditRefund"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Register+"'",
                ListButton.ajax("删除", ButtonType.ERROR,actionUrl("doDelete"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid").setConfirm("确定要删除吗？")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Done+"'&&formatDate(record.stockDate,'yyyyMM')=='"+month+"'&&(record.type=='"+StockInfo.Type_Stock+"'||record.type=='"+StockInfo.Type_Allocate+"')",
                ListButton.page("登记退货", ButtonType.GHOST,actionUrl("toView"), SuccessMethod.MUST_REFRESH)
                    .addParam("model.oid","oid").addQueryParam(Param.value("oper","refund"))
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Done+"'&&formatDate(record.stockDate,'yyyyMM')!='"+month+"'&&(record.type=='"+StockInfo.Type_Stock+"'||record.type=='"+StockInfo.Type_Allocate+"')",
                ListButton.page("登记退货出库", ButtonType.GHOST,actionUrl(SaleInfoAction.class,"toEditRefund"), SuccessMethod.REFRESH)
                    .addParam("model.refundStock.oid","oid")
            )
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.page("登记入库", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
        );
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("入库单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("入库客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("入库日期","stockDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("inputUser.oid", PowerUtil.getSessionUser(true).getOid()));
        result.addCondition(QueryCondition.not(QueryCondition.in("type",StockInfo.Type_Virtual,StockInfo.Type_Server)));
        return result;
    }
    /*
     * 审核列表
     */
    public VueResult checkList() throws Exception {
        VueListResult result=getVueListResult("入库待审核",StockInfo.class,actionUrl("checkList"));
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("入库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("入库客户", "guest.name", 100, true));
        result.addCol(toDateColumn("入库日期", "stockDate", 100, true));
        result.addCol(toNumberColumn("入库金额", "stockAmount", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        fillOrderColumn(result);
        if(PowerUtil.hasPower(PowerUtil.Stock)) {
            result.addCol(toSpaceColumn("操作", 100,
                ListElement.test("record.type=='"+StockInfo.Type_Stock+"'",
                    ListButton.page("审核", ButtonType.PRIMARY, actionUrl("toEdit"),  SuccessMethod.REFRESH)
                        .addParam("model.oid", "oid")
                ),
                ListElement.test("record.type=='"+StockInfo.Type_Refund+"'",
                    ListButton.page("退货审核", ButtonType.PRIMARY, actionUrl("toEditRefund"),  SuccessMethod.REFRESH)
                        .addParam("model.oid", "oid")
                )
            ).setFixed(Align.RIGHT));
        }
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("入库单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("入库客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("入库日期","stockDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("status",OrderModel.Status_Check));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.not(QueryCondition.in("type",StockInfo.Type_Virtual,StockInfo.Type_Server)));
        return result;
    }
    public VueResult selectOneChecked() throws Exception {
        String selected=getParamsValue("selected","");
        VueListResult result=getVueListResult("选择入库订单",StockInfo.class,actionUrl("selectOneChecked"));
        result.addQueryFields("oid");
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("入库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toDateColumn("入库日期", "stockDate", 100, true));
        result.addCol(toNumberColumn("入库金额", "stockAmount", 100, true));
        result.addCol(toNumberColumn("尚欠金额", "oweAmount", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        fillOrderColumn(result);
        result.addCol(toSpaceColumn("操作", 100,
            ListElement.test("record.oid!='"+selected+"'",
                ListButton.back("选择", ButtonType.PRIMARY)
                    .addParam("","")
            ),
            ListElement.elseOther(ListElement.tag("已选",""))
        ).setFixed(Align.RIGHT));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addSearch(ListSearch.field("客户","guest.oid",SearchType.HIDDEN_EQ));
        result.addCondition(QueryCondition.eq("status",OrderModel.Status_Done));
        result.addCondition(QueryCondition.in("type", StockInfo.Type_Stock,StockInfo.Type_Allocate,StockInfo.Type_Refund));
        result.addCondition(QueryCondition.not(QueryCondition.eq("oweAmount",0)));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.eq("inputUser.oid", PowerUtil.getSessionUserOid()));
        return result;
    }
    public VueResult queryList() throws Exception {
        VueListResult result=getVueListResult("入库订单查询",StockInfo.class,actionUrl("queryList"));
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("入库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("入库客户", "guest.name", 100, true));
        result.addCol(toDateColumn("入库日期", "stockDate", 100, true));
        result.addCol(toNumberColumn("入库金额", "stockAmount", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("入库单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("入库客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("入库日期","stockDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.not(QueryCondition.in("type",StockInfo.Type_Virtual,StockInfo.Type_Server)));
        return result;
    }
    public VueResult noSettleList() throws Exception {
        VueListResult result=getVueListResult("应付入库订单",StockInfo.class,actionUrl("noSettleList"));
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("入库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("入库客户", "guest.name", 100, true));
        result.addCol(toDateColumn("入库日期", "stockDate", 100, true));
        result.addCol(toNumberColumn("入库金额", "stockAmount", 100, true));
        result.addCol(toTextColumn("付款状态", "payStatus", 100, true).setDictType("m.store.model.StockInfo!payStatus"));
        result.addCol(toNumberColumn("付款金额", "payAmount", 100, true));
        result.addCol(toNumberColumn("尚欠金额", "oweAmount", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("入库单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("入库客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("入库日期","stockDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.not(QueryCondition.eq("oweAmount",0)));
        result.addCondition(QueryCondition.not(QueryCondition.in("type",StockInfo.Type_Virtual,StockInfo.Type_Server)));
        return result;
    }
    public StockInfo getModel() {
        return model;
    }

    public void setModel(StockInfo model) {
        this.model = model;
    }

    public List<GoodsStockRecord> getGoodsList() {
        return goodsList;
    }

    public void setGoodsList(List<GoodsStockRecord> goodsList) {
        this.goodsList = goodsList;
    }
}
